var adapterDataGrid = {
	$nodeAdapterDg: undefined,
	init: function () {
		if (this.$nodeAdapterDg != undefined) {
			this.$nodeAdapterDg.datagrid({
				width: '100%',
				rownumbers: true,
				singleSelect: true,
				fitColumns: true,
				emptyMsg: '暂无数据',
				title: '节点适配器',
				columns: [[
					{field: 'name', title: 'name', width: '48%', align: 'center'},
					{field: 'bundle', title: 'bundle', width: '37%', align: 'center'},
					{field: 'version', title: '版本号', width: '15%', align: 'center'}
				]]
			});
			this.$nodeAdapterDg = $('#nodeAdapterDg');
		}
	},
	fillData: function () {
		if (this.$nodeAdapterDg != undefined) {
			this.$nodeAdapterDg.datagrid('loadData', {
				total: AdapterCount,
				rows: adapterGather
			});

		}
	}

};
var nodeId="",nodeType="",nodeRemark;
var row="";
var nodeviewDataGrid = {
	$esbNodeTable: undefined,
	init: function () {
		if (this.$esbNodeTable != undefined) {
			this.$esbNodeTable.datagrid({
				width: '100%',
				singleSelect: true,
				fitColumns: true,
				emptyMsg: '暂无节点数据',
				title: '节点信息',
				columns: [[
					{field: 'nodeStatus', title: '状态', width: '8%', align: 'center',
						formatter: function (value, row, index) {
							return nodeviewDataGrid.formatStatus(value, row);
						}
					},
					{field: 'nodeName', title: '节点', width: '16%', align: 'center'
					},
					{field: 'netIp', title: 'IP', width: '18%', align: 'center'},
					{field: 'isRedisLive', title: 'redis', width: '8%', align: 'center',
						formatter: function (value, row, index) {
							return nodeviewDataGrid.formatStatus(value, row);
						}
					},
					{field: 'diskUsedPercentage', title: '磁盘已使用', width: '15%', align: 'center'},
					{field: 'serviceCount', title: '服务数量', width: '12%', align: 'center'},
					{field: 'version', title: '版本', width: '23%', align: 'center'}
				]]
			});
			this.$esbNodeTable = $('#esbNodeTable');
		}
	},
	formatStatus: function(value, row) {
		if (value == 1) {
			var startPic = '<img src="' + contextPath + '/images/console/green-pic.png" style="vertical-align: middle"/>';
			return startPic
		} else if (value == -2){
			var warnPic = '<img src="' + contextPath + '/images/console/yellow-pic.png" style="vertical-align: middle"/>';
			return warnPic
		}else {
			var stopPic = '<img src="' + contextPath + '/images/console/red-pic.png" style="vertical-align: middle"/>';
			return stopPic
		}
	},
	onLoadSuccess: function(){
		var tipIndex;
		$("#esbNodeContainer").mouseover(function(){
			//console.log("over");
			tipIndex = apexLayer.Tips({
				message:nodeRemark,
				more:false,
				guide:1,
				object:this,
				time:0
			});

		});
		$("#esbNodeContainer").mouseout(function(){
			//console.log("out");
			apexLayer.CloseIndex(tipIndex);
		});
		$("#esbNodeContainer").click(function(){
			getThreadPoolData(nodeId,nodeType);
			refleshChartsData(nodeId);
		});

	}
};

var cpuRatio,memoryRatio,threadRatio;
var currentNodeId = "",currnetNodeType = "";
$(function() {
	// 页面加载成功后重新获取DataGrid
	adapterDataGrid.$nodeAdapterDg = $('#nodeAdapterDg');
	// 必须先初始化adapter datagrid
	adapterDataGrid.init();
	// 填充数据
	adapterDataGrid.fillData();

	nodeviewDataGrid.$esbNodeTable = $('#esbNodeTable');
	nodeviewDataGrid.init();
	nodeviewDataGrid.onLoadSuccess();

	Highcharts.setOptions({
		global: {
			useUTC: false
		}
	});
	var task = setInterval(function(){
		refleshNodeData();
	},5000);

	initCpuChartObject();
	initMemoryChartObject();
	initThreadChartObject();

	var taskThread = setInterval(function(){
		getThreadPoolData(nodeId,nodeType);
	},10000);

	getThreadPoolData(nodeId,nodeType);
	refleshChartsData(nodeId);
	refleshNodeData();

});


function refleshNodeData(){
	var nodeStr = nodeId,nodeTypeStr = nodeType;
	getMonitorDataByNodeId(nodeStr,nodeTypeStr);

}

function getThreadPoolData(nodeId,nodeType){
	Ajax({
		url: contextPath+"/console/nodeStatus/pageQueryThreadPool",
		isMask : false,
		data: {
			nodeId: nodeId,
			nodeType: nodeType
		},
		success: function (data) {
			if(data.code>0){
				var obj = data.object;
				$("#Threads").text(obj.Threads);
				$("#MaxThreads").text(obj.MaxThreads);
				$("#IdleThreads").text(obj.IdleThreads);
				$("#IdleTimeout").text(obj.IdleTimeout);
				$("#MinThreads").text(obj.MinThreads);
				$("#UseThreads").text(obj.UseThreads);
			}else{
				$("#Threads").text("0");
				$("#MaxThreads").text("0");
				$("#IdleThreads").text("0");
				$("#IdleTimeout").text("0");
				$("#MinThreads").text("0");
				$("#UseThreads").text("0");

			}
		}
	});
}

function getMonitorDataByNodeId(nodeStr,nodeTypeStr){
	Ajax({
		url: contextPath+"/console/monitor/queryNodeDataByNodeId",
		isMask : false,
		timeout:0,
		data: {
			nodeStr: nodeStr,
			nodeTypeStr: nodeTypeStr
		},
		success: function (data) {
			if(data.code>0){
				var records = data.records;
				for(var i=0;i<records.length;i++){
					var row = records[i];
					var nodeId = row.nodeId;
					var nodeType = row.nodeType;
					nodeRemark = 'GUID:'+row.nodeGuid;
					if(row.code>0){
						var diskUsedPercentage = "0%";
						if(row.diskInfo!=undefined && row.diskInfo!=""
							&& row.diskInfo.diskUsedPercentage!=undefined && row.diskInfo.diskUsedPercentage!=""){
							diskUsedPercentage = row.diskInfo.diskUsedPercentage;
						}
						var nodeStatus;
						if(row.diskInfo.diskWarning==1){
							nodeStatus = -2;
							nodeRemark += "<br/>硬盘使用率达到预警值!";
						}else{
							nodeStatus = row.code;
						}
						var dataGridRows = [];
						var dataGridRow = {};
						//debugger;
						dataGridRow.nodeName = nodeJson.nodeName;
						dataGridRow.netIp = nodeJson.netIp;
						dataGridRow.version = nodeJson.version;
						dataGridRow.serviceCount = row.serviceCount;
						dataGridRow.diskUsedPercentage = diskUsedPercentage;
						dataGridRow.nodeStatus = nodeStatus;
						dataGridRow.isRedisLive = row.isRedisLive?"1":"-1";
						dataGridRows[0]= dataGridRow;
						//console.log(dataGridRows);
						nodeviewDataGrid.$esbNodeTable.datagrid('loadData', {
							total: dataGridRows.length,
							rows: dataGridRows
						});
					}else{
						var dataGridRows = [];
						var dataGridRow = {};
						dataGridRow.nodeName = row.nodeName;
						dataGridRow.netIp = row.netIp;
						dataGridRow.version = row.version;
						dataGridRow.serviceCount = 0;
						dataGridRow.diskUsedPercentage = "0%";
						dataGridRows[0]= dataGridRow;
						nodeviewDataGrid.$esbNodeTable.datagrid('loadData', {
							total: dataGridRows.length,
							rows: dataGridRows
						});

					}
				}
			}
		}
	});

}

function refleshChartsData(nodeId){

	Ajax({
		url: contextPath+"/console/monitor/queryChartsData",
		isMask : true,
		data: {
			nodeId: nodeId
		},
		success: function (data) {
			setChartsData(data,nodeId);
		}
	});

}
function setChartsData(result,nodeId){

	if(result.timeAry!=undefined &&
		result.cpuAry!=undefined &&
		result.memoryAry!=undefined &&
		result.threadAry!=undefined){

		var timeAry = result.timeAry;
		var cpuAry = result.cpuAry;
		var memoryAry = result.memoryAry;
		var threadAry = result.threadAry;

		var cpuChart,memoryChart,threadChart;
		var cpuRatioData = [],memoryRatioData = [],threadRatioData = [];
		for(var i=0;i<timeAry.length;i++){
			cpuRatioData.push([
				timeAry[i],
				cpuAry[i].data
			]);
			memoryRatioData.push([
				timeAry[i],
				memoryAry[i].data
			]);
			threadRatioData.push([
				timeAry[i],
				threadAry[i].data
			]);
		}
		//cpu使用率
		cpuRatio.series[0].data=cpuRatioData;
		cpuChart = new Highcharts.Chart(cpuRatio);
		//内存使用
		memoryRatio.series[0].data=memoryRatioData;
		memoryChart = new Highcharts.Chart(memoryRatio);
		//线程数
		threadRatio.series[0].data=threadRatioData;
		threadChart = new Highcharts.Chart(threadRatio);

	}
}
function initCpuChartObject(){
	cpuRatio={
		credits:{
			enabled:false // 禁用版权信息
		},
		chart: {
			type: 'spline',
			renderTo:'container_1',
			animation: Highcharts.svg, // don't animate in old IE
			marginRight: 10,
			events: {
				load: function () {
					var series = this.series[0];
					setInterval(function () {
						Ajax({
							url: contextPath+"/console/monitor/queryLastChartsData",
							isMask : false,
							data: {
								nodeId: nodeId,
								type: "cpuAry"
							},
							success: function (result) {

								if(series.data!=undefined && series.data.length>=24){
									series.data[0].remove();
								}
								var ary = new Array();
								ary[0]= result.key;
								ary[1]= result.value;
								if(result.warning==1){
									$("#"+nodeId).attr("cpu","CPU使用率到达预警值!")
								}else{
									$("#"+nodeId).attr("cpu","")
								}
								series.addPoint(ary);
							}
						});
					}, 5000);
				}
			}
		},
		title: {
			text: 'CPU使用率'
		},
		xAxis: {
			type: 'datetime',
			tickPixelInterval: 150
		},
		yAxis: {
			title: {
				text: '使用百分比 (%)'
			},
			min:0,
			max:100,
			plotLines: [{
				value: 0,
				width: 1,
				color: '#808080'
			}]
		},
		tooltip: {
			formatter: function () {
				return '<b>' + this.series.name + '</b><br/>' +
					Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
					'CPU使用率(%)：'+Highcharts.numberFormat(this.y, 2);
			}
		},
		legend: {
			enabled: false
		},
		exporting: {
			enabled: false
		},
		series: [{
			name: 'CPU使用率'
		}]
	};
}
function initMemoryChartObject(){
	memoryRatio={
		credits:{
			enabled:false // 禁用版权信息
		},
		chart: {
			type: 'spline',
			renderTo:'container_2',
			animation: Highcharts.svg, // don't animate in old IE
			marginRight: 10,
			events: {
				load: function () {
					var series = this.series[0];
					setInterval(function () {
						Ajax({
							url: contextPath+"/console/monitor/queryLastChartsData",
							isMask : false,
							data: {
								nodeId: nodeId,
								type: "memoryAry"
							},
							success: function (result) {

								if(series.data!=undefined && series.data.length>=24){
									series.data[0].remove();
								}
								var ary = new Array();
								ary[0]= result.key;
								ary[1]= result.value;
								if(result.warning==1){
									$("#"+nodeId).attr("memory","内存使用率到达预警值!")
								}else{
									$("#"+nodeId).attr("memory","")
								}
								series.addPoint(ary);
							}
						});
					}, 5000);
				}
			}
		},
		title: {
			text: '内存使用'
		},
		xAxis: {
			type: 'datetime',
			tickPixelInterval: 150
		},
		yAxis: {
			title: {
				text: '使用内存数(M)'
			},
			min:0,
//				max:10,
			plotLines: [{
				value: 0,
				width: 1,
				color: '#808080'
			}]
		},
		tooltip: {
			formatter: function () {
				return '<b>' + this.series.name + '</b><br/>' +
					Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
					'内存使用'+ this.y +'M';
			}
		},
		legend: {
			enabled: false
		},
		exporting: {
			enabled: false
		},
		series: [{
			name: '内存使用'
		}]
	};
}
function initThreadChartObject(){
	threadRatio={
		credits:{
			enabled:false // 禁用版权信息
		},
		chart: {
			type: 'spline',
			renderTo:'container_3',
			animation: Highcharts.svg, // don't animate in old IE
			marginRight: 10,
			events: {
				load: function () {
					var series = this.series[0];
					setInterval(function () {
						Ajax({
							url: contextPath+"/console/monitor/queryLastChartsData",
							isMask : false,
							data: {
								nodeId: nodeId,
								type: "threadAry"
							},
							success: function (result) {

								if(series.data!=undefined && series.data.length>=24){
									series.data[0].remove();
								}
								var ary = new Array();
								ary[0]= result.key;
								ary[1]= result.value;
								series.addPoint(ary);
							}
						});
					}, 5000);
				}
			}
		},
		title: {
			text: '线程数'
		},
		xAxis: {
			type: 'datetime',
			tickPixelInterval: 150
		},
		yAxis: {
			title: {
				text: '占用线程数(个)'
			},
			min:0,
			plotLines: [{
				value: 0,
				width: 1,
				color: '#808080'
			}]
		},
		tooltip: {
			formatter: function () {
				return '<b>' + this.series.name + '</b><br/>' +
					Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
					'线程占用'+ this.y +'个';
			}
		},
		legend: {
			enabled: false
		},
		exporting: {
			enabled: false
		},
		series: [{
			name: '线程数'
		}]
	};
}
